package com.qianchang.microfinance.view.home;

import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.DMLog;
import com.dm.library.utils.FormatUtil;
import com.dm.library.utils.ToastUtil;
import com.dm.library.widgets.element.DTextView;
import com.dm.library.widgets.indexlib.IndexBar.widget.DividerItemDecoration;
import com.google.gson.Gson;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.Apps;
import com.qianchang.microfinance.bean.BaseProduct;
import com.qianchang.microfinance.bean.CallRecords;
import com.qianchang.microfinance.bean.Contacts;
import com.qianchang.microfinance.bean.CooperationBean;
import com.qianchang.microfinance.bean.FindGuideBean;
import com.qianchang.microfinance.bean.FindUserBasicInfoBean;
import com.qianchang.microfinance.bean.FindsBean;
import com.qianchang.microfinance.bean.HomeAdvBean;
import com.qianchang.microfinance.bean.LoanType;
import com.qianchang.microfinance.bean.MineUserInfo;
import com.qianchang.microfinance.bean.MobileInfoBean;
import com.qianchang.microfinance.bean.PageBean;
import com.qianchang.microfinance.bean.PhoneGPSBean;
import com.qianchang.microfinance.bean.Product;
import com.qianchang.microfinance.bean.ProductBean;
import com.qianchang.microfinance.bean.PullGPSBean;
import com.qianchang.microfinance.bean.SMSInfoBean;
import com.qianchang.microfinance.bean.UserLoginInfo;
import com.qianchang.microfinance.global.ConstantAppInfo;
import com.qianchang.microfinance.global.DMApplication;
import com.qianchang.microfinance.gpsmanager.GPSLocationListener;
import com.qianchang.microfinance.gpsmanager.GPSProviderStatus;
import com.qianchang.microfinance.gpsmanager.LocationGPSManager;
import com.qianchang.microfinance.utils.ContactInforManger;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.utils.LocalAppManager;
import com.qianchang.microfinance.utils.UUIDS;
import com.qianchang.microfinance.view.WelComeToUrlActivity;
import com.qianchang.microfinance.view.base.BaseFragment;
import com.qianchang.microfinance.view.credit.data.BindBankCardActivity;
import com.qianchang.microfinance.view.credit.data.ConfirmInfoJinbaoActivity;
import com.qianchang.microfinance.view.credit.data.ScanFaceActivity;
import com.qianchang.microfinance.view.credit.data.ScanIdentityActivity;
import com.qianchang.microfinance.view.dialog.alert.DimengConfirmAlertDialog;
import com.qianchang.microfinance.view.dialog.alert.DimengSingleButtonAlertDialog;
import com.qianchang.microfinance.view.home.cash.ApplyCashActivity;
import com.qianchang.microfinance.view.hsbindbank.HSBindBankCardActivity;
import com.qianchang.microfinance.view.hsdialog.OpenedMemberDialog;
import com.qianchang.microfinance.view.hsrecharge.HSReChargeAuthorizedActivity;
import com.qianchang.microfinance.view.login.LoginActivity;
import com.qianchang.microfinance.view.mine.bill.MyBillActivity;
import com.qianchang.microfinance.view.mine.loan.HSQuickenWithdrawActivity;
import com.qianchang.microfinance.widgets.RecyclerViewDivider;
import com.qianchang.microfinance.widgets.glidetransform.GlideRoundTransform;
import com.umeng.analytics.MobclickAgent;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 版 权: 深圳市迪蒙网络科技有限公司
 * 描 述: <描述>
 * 修 改 人: sushuo
 * 修改时间: 2017-5-26
 */

public class HomeFragment extends BaseFragment {

    private static final String TAG = "HomeFragment";
    public static final String ENTITY_KEY = "ENTITY_KEY";



    @BindView(R.id.home_banner)
    Banner homeBanner;
    @BindView(R.id.refresh_home)
    SwipeRefreshLayout refreshHome;
    @BindView(R.id.tv_home_status)
    TextView tvHomeStatus;
    @BindView(R.id.iv_loan_status)
    ImageView ivLoanStatus;
    @BindView(R.id.btn_home_two_payback)
    Button btnHomeTwoPayback;
    @BindView(R.id.btn_home_one_borrow)
    Button btnHomeOneBorrow;
    @BindView(R.id.ll_get_amount)
    LinearLayout llGetAmount;
    @BindView(R.id.ll_has_amount)
    LinearLayout llHasAmount;
    @BindView(R.id.tv_usable_amount)
    DTextView tvUsableAmount;
    @BindView(R.id.iv_banner_bg)
    ImageView ivBannerBg;
    @BindView(R.id.tv_note_id)
    DTextView tvNote;                 //2017.12.15鸿胜科技新增
    @BindView(R.id.recyclerView)
    RecyclerView rcView;                        //2017.12.18鸿胜科技新增
    private ProductListAdapter adapter;
    @BindView(R.id.tv_speed_up_id)
    DTextView tvspeedUp;


    Unbinder unbinder;
    private static HomeFragment instant;
    private FindUserBasicInfoBean basicInfoBean;
    private List<HomeAdvBean> bannerList;
    private JsonResult<FindUserBasicInfoBean> mResponse;
    private List<Product> productList;
    private MineUserInfo mineUserInfo;

    @Override
    public void onResume() {
        super.onResume();
        //获取服务器数据
        getDataFromServer();
//        getUserInfo();
        onRefershProdData();
        //获取消费金融项目
        initProductData();      //2017.12.19鸿胜科技新增
        //获取GPS定位
        startLocationGPS();             //2017.12.27鸿盛科技新加

        MobclickAgent.onPageStart("首页HomeFragment");         //友盟统计 Fragment  页面统计
    }

    @Override
    public void onPause() {
        super.onPause();

        MobclickAgent.onPageEnd("首页HomeFragment");       //友盟统计 Fragment  页面统计
    }

    @Override
    public void onDetach() {
        super.onDetach();
        stopGPSLocation();          //2017.12.27鸿盛科技新加
        unbinder.unbind();
    }

    public static BaseFragment getInstance() {
        if (instant == null) {
            instant = new HomeFragment();
        }
        return instant;
    }


    @Override
    protected View onRootViewCreate(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_home, container, false);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    //从服务器获取banner的图片加载地址
    private void getDataFromServer() {
        getImagesUrl();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            getDataFromServer();
//            getUserInfo();            //摒弃不用
            onRefershProdData();
            initProductData();      //2017.12.19鸿胜科技新增\
            startLocationGPS();                     //2017.12.27鸿盛科技新加
        }
    }

    private void onRefershProdData(){
        if(adapter != null){
            adapter.clearData();
        }
    }


    private RecyclerViewDivider recyclerViewDivider;
    private LinearLayoutManager linearLayoutManager;

    @Override
    protected void initView() {
        super.initView();
        initProductRecyclerView();             //2014.12.20 鸿胜科技新增
        refreshHome.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getDataFromServer();
//                getUserInfo();                //摒弃不用
                onRefershProdData();
                initProductData();                  //2017.12.19鸿胜科技新增
                startLocationGPS();                 //2017.12.27鸿盛科技新加
            }
        });
    }

    @Override
    public void initData() {
        super.initData();

    }

    //获取用户最新基本信息
    private void updateStatus() {
        HttpParams params = new HttpParams();
        DMOKHttpUtils.getInstance().post(mContext, DMConstant.ApiURL.FIND_USER_BASIC_INFO, params, new RequestCallBack<FindUserBasicInfoBean>() {

            @Override
            public void onSuccess(JsonResult<FindUserBasicInfoBean> response) {
                mResponse = response;
                refreshHome.setRefreshing(false);
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    //刷新UI
                    refreshView(response.getObject());
                    getUserInfo();
                } else {
                    basicInfoBean = new FindUserBasicInfoBean();
                    basicInfoBean.setIsFirstAuth(1);
                    refreshView(basicInfoBean);
                    if (!"300001".equals(response.getCode())) {
                        if (!"300084".equals(response.getCode())) {
                            ToastUtil.getInstant().show(mContext, response.getDescription());
                        }
                    } else {
                        DMApplication.getInstance().setUserLoginInfo(null);
                    }
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                if (null != refreshHome)
                    refreshHome.setRefreshing(false);
                basicInfoBean = new FindUserBasicInfoBean();
                ToastUtil.getInstant().show(mContext, msg);
                refreshView(basicInfoBean);
            }

            @Override
            public void onConnectFailure(String msg) {
            }

        });
    }

    //刷新UI
    private void refreshView(FindUserBasicInfoBean bean) {
        try{
            basicInfoBean = bean == null ? new FindUserBasicInfoBean() : bean;
            tvUsableAmount.setTextContent(FormatUtil.numKbPointFormat(basicInfoBean.getLoanLimit()));         //2018.1.28注释迪蒙代码
            btnHomeOneBorrow.setEnabled(true);
            switch (basicInfoBean.getIsFirstAuth()) {
                case 0://(认证过，有额度，未借款)
                    //可用额度(未借款)
                    llGetAmount.setVisibility(View.GONE);
                    llHasAmount.setVisibility(View.VISIBLE);
                    btnHomeTwoPayback.setVisibility(View.GONE);
                    btnHomeOneBorrow.setText(getString(R.string.loan_money));
                    tvHomeStatus.setText(getString(R.string.receive_amount_now));
                    ivLoanStatus.setImageResource(R.drawable.img_hqed);
                    btnHomeOneBorrow.setEnabled(true);
                    break;
                case 1:
                    //无额度
                    llGetAmount.setVisibility(View.VISIBLE);
                    llHasAmount.setVisibility(View.GONE);
                    btnHomeTwoPayback.setVisibility(View.GONE);
//                btnHomeOneBorrow.setText(getString(R.string.btn_test_credit_quota));    //注释原来迪蒙代码 2018.1.20
                    btnHomeOneBorrow.setText(getString(R.string.loan_money));                   //新增鸿盛代码2018.1.20
                    tvHomeStatus.setText(getString(R.string.Label_no_quota));
                    ivLoanStatus.setImageResource(R.drawable.img_swed);
                    btnHomeOneBorrow.setEnabled(true);

                    tvNote.setText(getString(R.string.hight_borw));             //2017.12.15 鸿胜新增加
                    tvHomeStatus.setText(getString(R.string.hight_money));      //2017.12.15 鸿胜新增加
                    tvHomeStatus.setTextSize(TypedValue.COMPLEX_UNIT_SP, 38);    //2017.12.15 鸿胜新增加
                    break;

                case 2:
                    //正在获取额度
                    btnHomeOneBorrow.setEnabled(false);
                    llGetAmount.setVisibility(View.VISIBLE);
                    llHasAmount.setVisibility(View.GONE);
                    btnHomeTwoPayback.setVisibility(View.GONE);
                    btnHomeOneBorrow.setText(getString(R.string.loan_money));
                    tvHomeStatus.setText(getString(R.string.receive_amount_now));
                    ivLoanStatus.setImageResource(R.drawable.img_hqed);
                    btnHomeOneBorrow.setEnabled(false);
                    break;

                case 3:
                    //可用额度(已经借款)
                    llGetAmount.setVisibility(View.GONE);
                    llHasAmount.setVisibility(View.VISIBLE);
                    btnHomeTwoPayback.setVisibility(View.GONE);                     //鸿胜科技修改为 View.GONE 2018.1.17
                    btnHomeOneBorrow.setText(getString(R.string.loan_money));
                    btnHomeOneBorrow.setEnabled(true);

                    tvNote.setText(getString(R.string.available_amount));             //2017.12.15 鸿胜新增加
                    break;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    //初始化banner
    private void initBanner(List<HomeAdvBean> bannerDataList) {
        if (bannerDataList != null && !bannerDataList.isEmpty()) {
            ivBannerBg.setVisibility(View.GONE);
            homeBanner.setVisibility(View.VISIBLE);
            homeBanner.setImages(bannerDataList);
            homeBanner.setDelayTime(3000);
            homeBanner.isAutoPlay(true);

            homeBanner.setImageLoader(new ImageLoader() {
                @Override
                public void displayImage(Context context, Object path, ImageView imageView) {
                    if (null != imageView && null != path && path instanceof HomeAdvBean) {
                        HomeAdvBean homeAdvBean = (HomeAdvBean) path;
                        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                        Glide.with(context).load(homeAdvBean.getPictureUrl()).fitCenter().transform(new GlideRoundTransform(mContext, 0)).error(R.drawable.banner).into(imageView);      //DMConstant.Config.BASE_URL +
                    }
                }
            });
            //点击跳转至H5页面
            homeBanner.setOnBannerListener(new OnBannerListener() {
                @Override
                public void OnBannerClick(int position) {
                    if (null != bannerList && bannerList.size() > 0) {
                        String partnerUrl = bannerList.get(position).getPartnerUrl();
                        Bundle bundle = new Bundle();
                        bundle.putString("url", partnerUrl);
                        startActivity(WelComeToUrlActivity.class, bundle);

                        /*** 2018.1.28注释**
                         if (!TextUtils.isEmpty(partnerUrl) && FormatUtil.validateUrl(partnerUrl)) {
                         Bundle bundle = new Bundle();
                         bundle.putString("url", partnerUrl);
                         startActivity(WelComeToUrlActivity.class, bundle);
                         }
                         ***/

                    }
                }
            });
            homeBanner.start();
        } else {
            ivBannerBg.setVisibility(View.VISIBLE);
            homeBanner.setVisibility(View.GONE);
        }
    }


    @OnClick({R.id.btn_home_two_payback, R.id.btn_home_one_borrow, R.id.tv_increase_amount, R.id.tv_speed_up_id})
    public void onViewClicked(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.btn_home_two_payback:
                startActivity(MyBillActivity.class);  //还款 跳转我的账单

//                getMobileInfo();        //测试使用
                break;
            case R.id.btn_home_one_borrow:
                if (DMApplication.getInstance().isLogin()) {
                    if (mResponse != null) {
                        if ("300084".equals(mResponse.getCode())) {
                            DimengSingleButtonAlertDialog.newInstance("", mResponse.getDescription()).show(getFragmentManager(), getClass().getSimpleName());
                        } else {
                            if (null != basicInfoBean) {
                                if (basicInfoBean.getCashProductStatus() != 0) {
                                    ToastUtil.getInstant().show(mContext, "产品正在维护中，请稍后再试！");
                                    return;
                                }
                                bundle.putString(ConstantAppInfo.PROJECT_TYPE, LoanType.JBD);

                                switch (basicInfoBean.getIsFirstAuth()) {
                                    case 1:
                                        //未认证过
//                                        startActivity(ConfirmInfoJinbaoActivity.class, bundle);             //2018.1.18占时注释迪蒙代码

                                        if (basicInfoBean.getIsNewQianpen() != 0) {                   //判断是否是钱盆新用户0：是，1：否
                                            ToastUtil.getInstant().show(getContext(), "系统检测到您当前帐号不符号我们平台贷款要求！");
                                            return;
                                        }

                                        //鸿胜科技新增2018.1.18  如果未实名认证跳转实名认证 2018.1.18新加自己逻辑
                                        if (basicInfoBean.getIsIdCardCheckThrough() != 0) {                           // 判断是否实名验证过：0实名验证 1未验证
                                            bundle.putSerializable(ConstantAppInfo.BASIC_INFO_BEAN, basicInfoBean);
                                            startActivity(ScanIdentityActivity.class, bundle);
                                            return;
                                        }

                                        if (basicInfoBean.getIsOpenAccount() != 0) {                      //是否新网银行开户授权0：是，1：否
                                            bundle.putSerializable(ConstantAppInfo.BASIC_INFO_BEAN, basicInfoBean);
//                                            startActivity(BindBankCardActivity.class, bundle);
                                            startActivity(ConfirmInfoJinbaoActivity.class, bundle);
                                            return;
                                        }

                                        if (basicInfoBean.getIsBankCardBind() != 0) {                        //银行卡是否绑定 0 是绑定过，1 未绑定
//                                            startActivity(HSBindBankCardActivity.class);                   //如果授权过新网银行绑定银行卡的授权，直接跳转至绑定银行卡页面
                                            startActivity(ConfirmInfoJinbaoActivity.class, bundle);
                                            return;
                                        }

                                        if (basicInfoBean.getIsAccountAuth() != 0) {                          //是否是新网银行充值，提现和还款的授权 0是 1否
                                            Intent intent = new Intent();
                                            intent.setClass(getActivity(), HSReChargeAuthorizedActivity.class);
                                            startActivity(intent);
                                            return;
                                        }


                                        /****  暂时注释会员等级判断
                                         if(mineUserInfo != null){
                                         int meberlvel = Integer.valueOf(mineUserInfo.getMemberLevel());             //meberlvel 大于0 是会员小余0不是会员
                                         if(meberlvel < 0 || meberlvel == 0){
                                         OpenedMemberDialog openedMemberDialog = OpenedMemberDialog.newInstance();
                                         bundle.putSerializable(ConstantAppInfo.BASIC_INFO_BEAN, basicInfoBean);
                                         openedMemberDialog.setArguments(bundle);
                                         openedMemberDialog.show(getFragmentManager(), "openedDialog");
                                         return;
                                         }
                                         }else {
                                         ToastUtil.getInstant().show(getContext(),"获取会员信息异常!");
                                         return;
                                         }
                                         ******/

                                        if (basicInfoBean.getFaceRecogniteResult() != 1) {               //判断人脸识别是否验证过 1已验证，0未认证
                                            bundle.putSerializable(ConstantAppInfo.BASIC_INFO_BEAN, basicInfoBean);
//                                            startActivity(ScanFaceActivity.class, bundle);
                                            startActivity(ConfirmInfoJinbaoActivity.class, bundle);
                                            return;
                                        }

                                        if (basicInfoBean.getIsContactInfo() != 0) {       //判断联系人信息是否提交过 //1未认证（未提交）  0已提交（已认证）
                                            startActivity(ConfirmInfoJinbaoActivity.class, bundle);
                                            return;
                                        }

                                        if (basicInfoBean.getIsMobile() != 0) {           //手机验证是否验证通过 0 是，1 否
                                            startActivity(ConfirmInfoJinbaoActivity.class, bundle);
                                            return;
                                        }


                                        if (basicInfoBean.getIsTongDunAuth() != 0) {          //同盾认证 0 是，1 否
                                            startActivity(ConfirmInfoJinbaoActivity.class, bundle);
                                            return;
                                        }

                                        if (basicInfoBean.getIsSesameAuth() != 0) {           //芝麻验证通过   0 是，1 否
                                            startActivity(ConfirmInfoJinbaoActivity.class, bundle);
                                            return;
                                        }
//                                        if (basicInfoBean.getIsHandIdCardAuth()==0 ) {           // 手持 0未认证，1审核中，2已认证
//                                            startActivity(ConfirmInfoJinbaoActivity.class, bundle);
//                                            return;
//                                        }
//                                        if (basicInfoBean.getIsEmailAuth() != 1) {           //邮箱验证通过   0 未认证 1：认证成功
//                                            startActivity(ConfirmInfoJinbaoActivity.class, bundle);
//                                            return;
//                                        }

                                        // isEmailAuth;  // 邮箱认证 0 未认证 1：认证成功
//                                        if(basicInfoBean.getIsWorkProof() != 0){             // 工作认证是否认证过 0 是，1 否
//                                            startActivity(ConfirmInfoJinbaoActivity.class, bundle);
//                                            return;
//                                        }

                                        startActivity(ConfirmInfoJinbaoActivity.class, bundle);

                                        //全部验证通过去借钱
//                                        bundle.putSerializable(ConstantAppInfo.BASIC_INFO_BEAN, basicInfoBean);
//                                        startActivity(ApplyCashActivity.class, bundle);

                                        break;
                                    case 2:
                                        //正在获取额度
                                        //                                startActivity(ApplyCashActivity.class, bundle);
                                        break;
                                    case 0: //认证过
                                    case 3: //可用额度(已经借款)
//测试使用占时注释
                                        if (basicInfoBean.getIsNewQianpen() != 0) {                   //判断是否是钱盆新用户0：是，1：否
                                            ToastUtil.getInstant().show(getContext(), "系统检测到您当前帐号不符号我们平台贷款要求！");
                                            return;
                                        }

                                        //鸿胜科技新增2018.1.18  如果未实名认证跳转实名认证 2018.1.18新加自己逻辑
                                        if (basicInfoBean.getIsIdCardCheckThrough() != 0) {           // 判断是否实名验证过：0实名验证 1未验证
                                            bundle.putSerializable(ConstantAppInfo.BASIC_INFO_BEAN, basicInfoBean);
                                            startActivity(ScanIdentityActivity.class, bundle);
                                            return;
                                        }

                                        if (basicInfoBean.getIsOpenAccount() != 0) {          //是否新网银行开户授权0：是，1：否
                                            bundle.putSerializable(ConstantAppInfo.BASIC_INFO_BEAN, basicInfoBean);
//                                            startActivity(BindBankCardActivity.class, bundle);
                                            startActivity(ConfirmInfoJinbaoActivity.class, bundle);
                                            return;
                                        }

                                        if (basicInfoBean.getIsBankCardBind() != 0) {                        //银行卡是否绑定 0 是绑定过，1 未绑定
//                                            startActivity(HSBindBankCardActivity.class);                   //如果授权过新网银行绑定银行卡的授权，直接跳转至绑定银行卡页面
                                            startActivity(ConfirmInfoJinbaoActivity.class, bundle);
                                            return;
                                        }

                                        if (basicInfoBean.getIsAccountAuth() != 0) {           //是否是新网银行充值，提现和还款的授权 0是 1否
                                            Intent intent = new Intent();
                                            intent.setClass(getActivity(), HSReChargeAuthorizedActivity.class);
                                            startActivity(intent);
                                            return;
                                        }

                                        /****  占时注释会议等级判断
                                         if(mineUserInfo != null){
                                         int meberlvel = Integer.valueOf(mineUserInfo.getMemberLevel());             //meberlvel 大于0 是会员小余0不是会员
                                         if(meberlvel < 0 || meberlvel == 0){
                                         OpenedMemberDialog openedMemberDialog = OpenedMemberDialog.newInstance();
                                         bundle.putSerializable(ConstantAppInfo.BASIC_INFO_BEAN, basicInfoBean);
                                         openedMemberDialog.setArguments(bundle);
                                         openedMemberDialog.show(getFragmentManager(), "openedDialog");
                                         return;
                                         }
                                         }else {
                                         ToastUtil.getInstant().show(getContext(),"获取会员信息异常!");
                                         return;
                                         }
                                         ******/

                                        if (basicInfoBean.getFaceRecogniteResult() != 1) {               //判断人脸识别是否验证过 1已验证，0未认证
                                            bundle.putSerializable(ConstantAppInfo.BASIC_INFO_BEAN, basicInfoBean);
//                                            startActivity(ScanFaceActivity.class, bundle);
                                            startActivity(ConfirmInfoJinbaoActivity.class, bundle);
                                            return;
                                        }

                                        if (basicInfoBean.getIsContactInfo() != 0) {       //判断联系人信息是否提交过 //1未认证（未提交）  0已提交（已认证）
                                            startActivity(ConfirmInfoJinbaoActivity.class, bundle);
                                            return;
                                        }

                                        if (basicInfoBean.getIsMobile() != 0) {           //手机验证是否验证通过 0 是，1 否
                                            startActivity(ConfirmInfoJinbaoActivity.class, bundle);
                                            return;
                                        }

                                        if (basicInfoBean.getIsTongDunAuth() != 0) {          //同盾认证 0 是，1 否
                                            startActivity(ConfirmInfoJinbaoActivity.class, bundle);
                                            return;
                                        }

                                        if (basicInfoBean.getIsSesameAuth() != 0) {           //芝麻验证通过   0 是，1 否
                                            startActivity(ConfirmInfoJinbaoActivity.class, bundle);
                                            return;
                                        }
//                                        if (basicInfoBean.getIsHandIdCardAuth()==0 ) {           // 手持 0未认证，1审核中，2已认证
//                                            startActivity(ConfirmInfoJinbaoActivity.class, bundle);
//                                            return;
//                                        }
//                                        if (basicInfoBean.getIsEmailAuth() != 1) {           //邮箱验证通过   0 未认证 1：认证成功
//                                            startActivity(ConfirmInfoJinbaoActivity.class, bundle);
//                                            return;
//                                        }
//                                        if(basicInfoBean.getIsWorkProof() != 0){             // 工作认证是否认证过 0 是，1 否
//                                            startActivity(ConfirmInfoJinbaoActivity.class, bundle);
//                                            return;
//                                        }


                                            bundle.putSerializable(ConstantAppInfo.BASIC_INFO_BEAN, basicInfoBean);
                                            startActivity(ApplyCashActivity.class, bundle);


                                        break;
                                }
                            }
                        }
                    }
                } else {
                    startActivity(LoginActivity.class);
                }
                break;
            case R.id.tv_increase_amount:
                //                startActivity(AccumlateCreditActivity.class);
                break;
            case R.id.tv_speed_up_id:       //加速提现
//                OpenedMemberDialog.newInstance().show(getFragmentManager(), "openedDialog");            //测试使用

//                startActivity(PhoneAuthActivity.class);             //测试使用
//                startActivity(GoSesameAuthorizedActivity.class);            //测试使用 芝麻

                startActivity(HSQuickenWithdrawActivity.class);             //测试使用


                break;
        }
    }


    public void getImagesUrl() {
        show(true);
        HttpParams params = new HttpParams();
        params.put("sendSide", "SEND_SIDE_2");
        DMOKHttpUtils.getInstance().post(mContext, DMConstant.ApiURL.FIND_SITE_LIST, params, new RequestCallBack<PageBean<HomeAdvBean>>() {
            @Override
            public void onSuccess(JsonResult<PageBean<HomeAdvBean>> response) {
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    bannerList = response.getObject().getList();
                    //初始化banner
                    initBanner(bannerList);
                    //更新状态
                    updateStatus();
                } else {
                    dismiss();
                    refreshHome.setRefreshing(false);
                    ToastUtil.getInstant().show(mContext, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                if(null != refreshHome){
                    refreshHome.setRefreshing(false);
                    ToastUtil.getInstant().show(mContext, msg);
                }
            }

            @Override
            public void onConnectFailure(String msg) {
                ToastUtil.getInstant().show(mContext, msg);
            }

        });
    }


    /**
     * 2017.12.18 鸿胜科技新增加
     * 获取产品列表
     */
    private void initProductData() {
        HttpParams params = new HttpParams();
        DMOKHttpUtils.getInstance().post(mContext, DMConstant.ApiURL.FIND_PRODUCT_FORAPPALL, params, new RequestCallBack<List<Product>>() {

            @Override
            public void onSuccess(JsonResult<List<Product>> response) {
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    productList = response.getObject();
                    initProductList(productList);
                    //引流产品
                    cooperation();                  //引流产品
                } else {
                    ToastUtil.getInstant().show(mContext, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                ToastUtil.getInstant().show(mContext, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
                ToastUtil.getInstant().show(mContext, msg);
            }
        });
    }


    /**
     * 初始化产品列表控件
     */
    private void initProductRecyclerView() {
        linearLayoutManager = new LinearLayoutManager(getActivity());
        rcView.setLayoutManager(linearLayoutManager);
        adapter = new ProductListAdapter(getActivity());
        rcView.setAdapter(adapter);
        recyclerViewDivider = new RecyclerViewDivider(getActivity(), DividerItemDecoration.VERTICAL_LIST);
        rcView.addItemDecoration(recyclerViewDivider);
        rcView.setHasFixedSize(true);
        rcView.setNestedScrollingEnabled(false);
        adapter.setOnItemClickListener(new ProductListAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(View view, int position) {

                BaseProduct baseProduct = (BaseProduct) adapter.getBaseTypeItems().get(position);
                if(baseProduct == null){
                    ToastUtil.getInstant().show(getContext(),"数据有误");
                    return;
                }else {
                    if(baseProduct.getBaseType() == adapter.PRODUCT_TYPE){          //自己的产品点击
                        if (productList != null) {
                            //适配器的item被点击时 根据用户的基本信息的认证进度进行跳转
                            int type = basicInfoBean.getIsFirstAuth();
                            switchLoanMoney(type,position);
                        }
                    }else if(baseProduct.getBaseType() == adapter.COOPERATION_TYPE){                //引流的产品点击
                        CooperationBean cooperationBean = (CooperationBean) adapter.getBaseTypeItems().get(position);
                        String id = cooperationBean.getId();
                        findGuideUR(id);
                    }
                }

            }
        });

    }

    /**
     * 2017.12.18 鸿胜科技新增加
     * 绑定产品数据
     */
    private void initProductList(List<Product> productList) {
        if (productList != null && !productList.isEmpty()) {
            adapter.setListProduct(productList);
        } else {
            adapter.clearData();
        }
    }


    /**
     *  获取合作的推荐产品引流产品数据
     */
    private void cooperation(){

        HttpParams params = new HttpParams();
        DMOKHttpUtils.getInstance().post(mContext, DMConstant.ApiURL.FIND_GUIDE_TABLIST, params, new RequestCallBack<PageBean<CooperationBean>>() {

            @Override
            public void onSuccess(JsonResult<PageBean<CooperationBean>> response) {
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    if(response.getObject() != null){
                        List<CooperationBean> findsBeanList = response.getObject().getList();
                        adapter.setCooperationBeanList(findsBeanList);
                    }
                } else {
                    ToastUtil.getInstant().show(mContext, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                ToastUtil.getInstant().show(mContext, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
                ToastUtil.getInstant().show(mContext, msg);
            }
        });

    }

    //获取导流产品URL
    private void findGuideUR(String id){

        HttpParams params = new HttpParams();
        params.put("id",id);

        show();
        DMOKHttpUtils.getInstance().post(getContext(), DMConstant.ApiURL.FIND_GUIDE_URL, params, new RequestCallBack<FindGuideBean>() {

            @Override
            public void onSuccess(JsonResult<FindGuideBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    FindGuideBean findGuideBean = response.getObject();
                    if(findGuideBean != null){
                        String url = findGuideBean.getAppURL();
                        initWb(url);
                    }else {
                        ToastUtil.getInstant().show(getContext(), "数据有误请稍后再试!");
                    }
                }else {
                    ToastUtil.getInstant().show(getContext(), response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(getContext(), msg);
            }

            @Override
            public void onConnectFailure(String msg) {
            }
        });
    }

    //调用外部浏览器打开
    private void initWb(String url){
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri content_url = Uri.parse(url);
        intent.setData(content_url);
        startActivity(intent);
    }


    private void uploadGPS(Location location) {

        DMApplication dmApplication = (DMApplication) getActivity().getApplicationContext();
        boolean islogin = dmApplication.isLogin();
        if (!islogin) {                       //判断是否登录没有登录不用提交GPS信息
            DMLog.e("没有登录不提交GPS!");
            return;
        }

        PhoneGPSBean phoneGPSBean = new PhoneGPSBean();
        UserLoginInfo userLoginInfo = DMApplication.getInstance().getmUserLoginInfo();
        String usid = userLoginInfo.getUserId();
        String deviceId = UUIDS.buidleID(getActivity().getApplicationContext()).getUUIDS();

        phoneGPSBean.setLatBD("");
        phoneGPSBean.setLngBD("");
        phoneGPSBean.setLatGPS(String.valueOf(location.getLatitude()));
        phoneGPSBean.setLngGPS(String.valueOf(location.getLongitude()));

//        phoneGPSBean.setLatGPS("22.832125");
//        phoneGPSBean.setLngGPS("108.371609");
        stopGPSLocation();                                              //拿到坐标后停止定位
        phoneGPSBean.setUniqueIndentification(deviceId);
        phoneGPSBean.setUserId(usid);
        Gson gson = new Gson();
        String paramsStr = gson.toJson(phoneGPSBean);

        DMOKHttpUtils.getInstance().postString(getActivity().getApplicationContext(), DMConstant.ApiURL.GET_MOBILE_GPS, paramsStr, new RequestCallBack<PullGPSBean>() {

            @Override
            public void onSuccess(JsonResult<PullGPSBean> response) {
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    PullGPSBean pullGPSBean = response.getObject();
                    isPullMobleInfo(pullGPSBean);
                } else {
                    ToastUtil.getInstant().show(mContext, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                ToastUtil.getInstant().show(mContext, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
                ToastUtil.getInstant().show(mContext, msg);
            }
        });
    }

    //判断是否需要提交手机联系人信息
    private void isPullMobleInfo(PullGPSBean pullGPSBean) {
        if (pullGPSBean != null) {
            boolean ispl = pullGPSBean.isPull();            //判断是否需要提交提交手机联系人信息
            if (ispl) {
                //需要提交
                getMobileInfo();
            } else {
                DMLog.i("不需要提交手机信息数据");
            }
        } else {
            DMLog.i("判断提交手机信息数据判断为空");
        }
    }

    private List<Contacts> listContacts = null;

    //获取手机信息
    private void getMobileInfo() {

        MobileInfoBean mobileInfoBean = new MobileInfoBean();
        LocalAppManager localAppManager = new LocalAppManager(getActivity().getApplicationContext());
        List<Apps> appsList = localAppManager.getAppInfos();    //获取手机应用数据
        if (appsList != null) {
            mobileInfoBean.setApps(appsList);
        }

        List<Contacts> listContacts = ContactInforManger.getContactsList(getActivity().getApplicationContext());    //获取手机联系人数据
        if (listContacts != null) {
            mobileInfoBean.setContacts(listContacts);
        }
        List<CallRecords> callRecordsList = ContactInforManger.getCallHistoryList(getActivity().getApplicationContext());   //获取手机通话记录
        if (callRecordsList != null) {
            mobileInfoBean.setCallRecords(callRecordsList);
        }

        List<SMSInfoBean> smsInfoBeanList = ContactInforManger.getSMSInfo(getActivity().getApplicationContext());   //获取手机短信记录
        if (smsInfoBeanList != null) {
            mobileInfoBean.setSmsInfoBeans(smsInfoBeanList);
        }
        UserLoginInfo userLoginInfo = DMApplication.getInstance().getmUserLoginInfo();
        String usid = userLoginInfo.getUserId();
        String deviceId = UUIDS.buidleID(getActivity().getApplicationContext()).getUUIDS();

        mobileInfoBean.setMobileType("android");
        mobileInfoBean.setUniqueIndentification(deviceId);
        mobileInfoBean.setUserId(usid);

        Gson gson = new Gson();
        String paramsStr = gson.toJson(mobileInfoBean);

        DMOKHttpUtils.getInstance().postString(getActivity().getApplicationContext(), DMConstant.ApiURL.GET_MOBILE_INFO, paramsStr, new RequestCallBack<Object>() {

            @Override
            public void onSuccess(JsonResult<Object> response) {
                DMLog.i(response.toString());   //若上传失败 。。。应做个尝试重新提交的方法
            }

            @Override
            public void onFailure(String msg) {
                ToastUtil.getInstant().show(getActivity(), msg);
            }

            @Override
            public void onConnectFailure(String msg) {
                ToastUtil.getInstant().show(getActivity(), msg);
            }
        });
    }


    /**
     * 开始打开本机GPS 请求定位
     */
    private void startLocationGPS() {
        stopGPSLocation();      //开始定位之前预防之前开启过定位的没有停止先停止定位
        LocationGPSManager.getInstance(getActivity().getApplicationContext()).start(gpsLocationListener, true);
    }

    /**
     * 停止定位
     */
    private void stopGPSLocation() {
        LocationGPSManager.getInstance(getActivity().getApplicationContext()).stop();
    }


    private GPSLocationListener gpsLocationListener = new GPSLocationListener() {

        int mGpsStatus = GPSProviderStatus.GPS_OUT_OF_SERVICE;

        @Override
        public void UpdateLocation(Location location) {
            double lat = location.getLatitude();
            double lng = location.getLongitude();
            DMLog.e("默认定位位置：lat=== " + lat + "  lng ====" + lng);

            /**
             * 当GPS可用的时候获取坐标
             */
            if (mGpsStatus == GPSProviderStatus.GPS_AVAILABLE) {
                DMLog.e("GPS可用了 定位位置：lat=== " + lat + "  lng ====" + lng);
                if (location != null) {
                    uploadGPS(location);
                }
            }
        }

        @Override
        public void UpdateStatus(String provider, int status, Bundle extras) {
            if ("gps" == provider) {
                DMLog.e("定位类型：" + provider);
            }
        }

        @Override
        public void UpdateGPSProviderStatus(int gpsStatus) {
            switch (gpsStatus) {
                case GPSProviderStatus.GPS_ENABLED:
                    mGpsStatus = GPSProviderStatus.GPS_ENABLED;
                    DMLog.e("GPS开启");
                    break;
                case GPSProviderStatus.GPS_DISABLED:
                    mGpsStatus = GPSProviderStatus.GPS_DISABLED;
                    DMLog.e("GPS关闭");
                    break;
                case GPSProviderStatus.GPS_OUT_OF_SERVICE:
                    mGpsStatus = GPSProviderStatus.GPS_OUT_OF_SERVICE;
                    DMLog.e("GPS不可用");
                    break;
                case GPSProviderStatus.GPS_TEMPORARILY_UNAVAILABLE:
                    mGpsStatus = GPSProviderStatus.GPS_TEMPORARILY_UNAVAILABLE;
                    DMLog.e("GPS暂时不可用");
                    break;
                case GPSProviderStatus.GPS_AVAILABLE:
                    mGpsStatus = GPSProviderStatus.GPS_AVAILABLE;
                    DMLog.e("GPS可用啦");
                    break;
            }
        }
    };


    /**
     * 2018.1.18鸿胜科技新增加
     */
    public void getUserInfo() {
        HttpParams params = new HttpParams();
        show();
        DMOKHttpUtils.getInstance().post(mContext, DMConstant.ApiURL.FIND_USER_INFO, params, new RequestCallBack<MineUserInfo>() {

            @Override
            public void onSuccess(JsonResult<MineUserInfo> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    mineUserInfo = response.getObject();
                    //获取用户额度上限
                    String borrowLimit = mineUserInfo.getBorrowLimit();
                    tvUsableAmount.setTextContent(FormatUtil.numKbPointFormat(borrowLimit));
                } else {
                    if (!"300001".equals(response.getCode())) {
                        if (!"300084".equals(response.getCode())) {
                            ToastUtil.getInstant().show(mContext, response.getDescription());
                        }
                    } else {
                        DMApplication.getInstance().setUserLoginInfo(null);
                    }
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(mContext, msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }

    private void switchLoanMoney(int type,int position) {
        Bundle bundle = new Bundle();
        bundle.putString(ConstantAppInfo.PROJECT_TYPE, LoanType.JBD);

        switch (type) {
            case 1:
                //未认证过
//              startActivity(ConfirmInfoJinbaoActivity.class, bundle);             //2018.1.18占时注释迪蒙代码

                if (basicInfoBean.getIsNewQianpen() != 0) {                   //判断是否是钱盆新用户0：是，1：否
                    ToastUtil.getInstant().show(getContext(), "系统检测到您当前帐号不符号我们平台贷款要求！");
                    return;
                }

                //鸿胜科技新增2018.1.18  如果未实名认证跳转实名认证 2018.1.18新加自己逻辑
                if (basicInfoBean.getIsIdCardCheckThrough() != 0) {           // 判断是否实名验证过：0实名验证 1未验证
                    bundle.putSerializable(ConstantAppInfo.BASIC_INFO_BEAN, basicInfoBean);
                    startActivity(ScanIdentityActivity.class, bundle);
                    return;
                }

                //如果未授权开户跳转新网开户授权
                if (basicInfoBean.getIsOpenAccount() != 0) {          //是否新网银行开户授权0：是，1：否
                    bundle.putSerializable(ConstantAppInfo.BASIC_INFO_BEAN, basicInfoBean);
                    startActivity(BindBankCardActivity.class, bundle);
                    return;
                }

                if (basicInfoBean.getIsBankCardBind() != 0) {                        //银行卡是否绑定 0 是绑定过，1 未绑定
                    startActivity(HSBindBankCardActivity.class);                   //如果授权过新网银行绑定银行卡的授权，直接跳转至绑定银行卡页面
                    return;
                }

                if (basicInfoBean.getIsAccountAuth() != 0) {           //是否是新网银行充值，提现和还款的授权 0是 1否
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), HSReChargeAuthorizedActivity.class);
                    startActivity(intent);
                    return;
                }

                /****  暂时注释会员等级判断
                 if(mineUserInfo != null){
                 int meberlvel = Integer.valueOf(mineUserInfo.getMemberLevel());             //meberlvel 大于0 是会员小余0不是会员
                 if(meberlvel < 0 || meberlvel == 0){
                 OpenedMemberDialog openedMemberDialog = OpenedMemberDialog.newInstance();
                 bundle.putSerializable(ConstantAppInfo.BASIC_INFO_BEAN, basicInfoBean);
                 openedMemberDialog.setArguments(bundle);
                 openedMemberDialog.show(getFragmentManager(), "openedDialog");
                 return;
                 }
                 }else {
                 ToastUtil.getInstant().show(getContext(),"获取会员信息异常!");
                 return;
                 }
                 ******/

                //如未认证跳转至人脸识别
                if (basicInfoBean.getFaceRecogniteResult() != 1) {               //判断人脸识别是否验证过 1已验证，0未认证
                    bundle.putSerializable(ConstantAppInfo.BASIC_INFO_BEAN, basicInfoBean);
                    startActivity(ScanFaceActivity.class, bundle);
                    return;
                }

                //如未进行联系人认证，则跳转至认证中心？
                if (basicInfoBean.getIsContactInfo() != 0) {       //判断联系人信息是否提交过 //1未认证（未提交）  0已提交（已认证）
                    startActivity(ConfirmInfoJinbaoActivity.class, bundle);
                    return;
                }

                //如未进行手机认证，则也跳转至认证中心？
                if (basicInfoBean.getIsMobile() != 0) {           //手机验证是否验证通过 0 是，1 否
                    startActivity(ConfirmInfoJinbaoActivity.class, bundle);
                    return;
                }

                //如未进行同盾认证，则跳转至认证中心？
                if (basicInfoBean.getIsTongDunAuth() != 0) {          //同盾认证 0 是，1 否
                    startActivity(ConfirmInfoJinbaoActivity.class, bundle);
                    return;
                }

                //如未进行芝麻认证，则跳转至认证中心？
                if (basicInfoBean.getIsSesameAuth() != 0) {           //芝麻验证通过   0 是，1 否
                    startActivity(ConfirmInfoJinbaoActivity.class, bundle);
                    return;
                }

                //如未进行工作认证，则跳转到认证中心
                if (basicInfoBean.getIsWorkProof() != 0) {             // 工作认证是否认证过 0 是，1 否
                    startActivity(ConfirmInfoJinbaoActivity.class, bundle);
                    return;
                }
                if (basicInfoBean.getIsHandIdCardAuth()==0 ) {           // 手持 0未认证，1审核中，2已认证
                    startActivity(ConfirmInfoJinbaoActivity.class, bundle);
                    return;
                }
                if (basicInfoBean.getIsEmailAuth() != 1) {           //邮箱验证通过   0 未认证 1：认证成功
                    startActivity(ConfirmInfoJinbaoActivity.class, bundle);
                    return;
                }
                //全部验证通过去借钱

                bundle.putSerializable(ConstantAppInfo.BASIC_INFO_BEAN, basicInfoBean);
                startActivity(ApplyCashActivity.class, bundle);

                break;
            case 2:
                //正在获取额度
                //                                startActivity(ApplyCashActivity.class, bundle);
                break;
            case 0: //认证过
            case 3: //可用额度(已经借款)

                if (basicInfoBean.getIsNewQianpen() != 0) {                   //判断是否是钱盆新用户0：是，1：否
                    ToastUtil.getInstant().show(getContext(), "系统检测到您当前帐号不符号我们平台贷款要求！");
                    return;
                }

                if (basicInfoBean.getIsAccountAuth() != 0) {           //是否是新网银行充值，提现和还款的授权 0是 1否
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), HSReChargeAuthorizedActivity.class);
                    startActivity(intent);
                    return;
                }
                //获取产品
                Product productBean = adapter.getItems().get(position);
                bundle.putSerializable(ConstantAppInfo.BASIC_INFO_PROJECT, productBean);
                bundle.putSerializable(ConstantAppInfo.BASIC_INFO_BEAN, basicInfoBean);
                startActivity(ApplyCashActivity.class, bundle);
                break;
        }
    }


}



